package com.android.kmobi.locket.mpcontrol;

import java.io.IOException;
import com.android.kmobi.locket.receiver.LocketReceiver;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.SystemClock;

public class MpControl {
	
	private static MpControl mMpControl;
	private Context mContext;
	
	public MpControl(Context context) {
		mContext = context.getApplicationContext();
	}
	
	private boolean initReceiver;
	private void registerReceiver() {
		if(!initReceiver)
		{
			initReceiver = true;
			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_SCREEN_ON);
			filter.addAction(Intent.ACTION_USER_PRESENT);
		    filter.addAction(Intent.ACTION_SCREEN_OFF);
		    filter.setPriority(Integer.MAX_VALUE);
		    mLocketReceiver.setIsStaticReceiver(false);
		    mContext.registerReceiver(mLocketReceiver, filter);
		}
	}
	
	private void unRegisterReceiver() {
		if(initReceiver)
		{
			mContext.unregisterReceiver(mLocketReceiver);
			initReceiver = false;
		}
	}
	
	private static final long clockTime = 300000L;
	public void init() {
		registerReceiver();
		delayTimeStart(clockTime);//5分钟注册一次亮屏事件
	}
	
	public void unInit() {
		unRegisterReceiver();
		mContext = null;
		mMpControl = null;
	}
	
	public static MpControl getInstance(Context context) {
		if(mMpControl==null)
		{
			mMpControl = new MpControl(context);
		}
		return mMpControl;
	}
	
	private int audioStreamType = AudioManager.STREAM_RING;//铃声播报类型
	
	private boolean finish = false;
	/**
	 * 播放提示音
	 */
	public void playTone(final String music_assets) {
		boolean exception = false;
		final MediaPlayer mediaPlayer = new MediaPlayer();
		try {
			AssetFileDescriptor fileDescriptor = mContext.getAssets().openFd(music_assets);
			if(fileDescriptor!=null)
			{
				mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());
				mediaPlayer.setOnCompletionListener(playToneOnCompletionListener);
				mediaPlayer.setAudioStreamType(audioStreamType);
				new Thread() {
					public void run() {
						boolean exception = false;
						try {
							mediaPlayer.prepare();
							mediaPlayer.start();
						} catch (IllegalStateException e) {
							exception = true;
						} catch (IOException e) {
							exception = true;
						} catch (Exception e) {
							exception = true;
						}
						if(exception)
						{
							playToneOnCompletionListener.onCompletion(mediaPlayer);
						}
					}
				}.start();
			}
			else
			{
				exception = true;
			}
		} catch (IllegalArgumentException e) {
			exception = true;
		} catch (SecurityException e) {
			exception = true;
		} catch (IllegalStateException e) {
			exception = true;
		} catch (IOException e) {
			exception = true;
		} catch (Exception e) {
			exception = true;
		}
		if(exception)
		{
			playToneOnCompletionListener.onCompletion(mediaPlayer);
		}
	}
	
	private long lastCreateClockTime;
	/**
	 * 延时启动
	 * @param interval
	 */
	private void delayTimeStart(long interval) {
		long currentTime = System.currentTimeMillis();
		if(lastCreateClockTime==0||lastCreateClockTime>(currentTime+clockTime))
		{
			lastCreateClockTime = currentTime;
			cancleClock();
			createClock(interval);
		}
	}
	
	private static final String CLOCK_WAKEUP_ACTION = "com.android.kmobi.locket.WAKE_UP";
	private void createClock(long interval) {
		AlarmManager alarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);  
		Intent intent = new Intent(mContext, LocketReceiver.class);
		intent.setAction(CLOCK_WAKEUP_ACTION);
		PendingIntent pendIntent = PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		// 5秒后发送广播，只发送一次  
		long triggerAtTime = SystemClock.elapsedRealtime() + interval;
		alarmMgr.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, pendIntent);
	}
	
	private void cancleClock() {
		AlarmManager alarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(mContext, LocketReceiver.class);
		intent.setAction(CLOCK_WAKEUP_ACTION);
		PendingIntent pendIntent = PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		alarmMgr.cancel(pendIntent);
	}
	
	
	/**
	 * 播放结束的处理
	 */
	private final  OnCompletionListener playToneOnCompletionListener = new OnCompletionListener(){
		@Override
		public void onCompletion(MediaPlayer mp) {
			
		}
	};
	
	private final LocketReceiver mLocketReceiver = new LocketReceiver();

}
